#include "VideoRendererAdapter.h"
#include <assert.h>

VideoRendererAdapter::VideoRendererAdapter(rtc::scoped_refptr<webrtc::VideoTrackInterface> rendered_track,
	VideoRenderer *external_renderer,
	VideoFrameType frame_type_needed)
	:rendered_track_(rendered_track),
	external_renderer_(external_renderer),
	frame_type_needed_(frame_type_needed)
{
	assert(external_renderer_);
	rendered_track_->AddRenderer(this);
}

VideoRendererAdapter::~VideoRendererAdapter()
{
	rendered_track_->RemoveRenderer(this);
}

void VideoRendererAdapter::SetSize(int width, int height)
{
	external_renderer_->SetSize(width, height);
}

void VideoRendererAdapter::RenderFrame(const cricket::VideoFrame* video_frame)
{
	const cricket::VideoFrame* frame =
		video_frame->GetCopyWithRotationApplied();
	int width = frame->GetWidth();
	int height = frame->GetHeight();

	switch (frame_type_needed_)
	{
	case kARGB:
	{
		rtc::scoped_ptr<uint8[]> image_;
		int bit_count = 32;
		SetSize(width, height);
		int frame_size = width * height * (32 >> 3);
		image_.reset(new uint8[frame_size]);

		frame->CopyToBuffer(image_.get(), (width * height * 3) /2);

		cricket::VideoFrame *new_video_frame = frame->Copy();
		new_video_frame->Reset(cricket::FOURCC_I420, width, height, width, height, image_.get(), (width * height * 3) / 2, width, height, 0, 0, webrtc::kVideoRotation_180, true);
		new_video_frame->ConvertToRgbBuffer(cricket::FOURCC_ARGB,
			image_.get(),
			frame_size,
			width * bit_count / 8);
		external_renderer_->RenderFrame((const char *)image_.get(), frame_size);

		delete new_video_frame;
	}
		break;
	case kI420:
	{
		rtc::scoped_ptr<uint8[]> image_;
		SetSize(width, height);
		int frame_size = (width * height * 3) /2;
		image_.reset(new uint8[frame_size]);
		frame->CopyToBuffer(image_.get(), frame_size);
		external_renderer_->RenderFrame((const char *)image_.get(), frame_size);
	}
		break;
	default:
		break;
	}
}

bool VideoRendererAdapter::CanApplyRotation()
{
	return false;
}


